package com.ruoyi.sms.util;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.sms.config.SmsSendConfig;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import java.util.Date;

/**
 * 短信签名工具类
 */
@Slf4j
public class SmsSignUtil {

    /**
     * BASE64加密
     */
    public JSONObject encryptBASE64(){
        SmsSendConfig smsSendConfig = com.ruoyi.sms.common.SpringContextUtil.getBean(SmsSendConfig.class);
        JSONObject jsonObject = new JSONObject();
        long timestamp = getSecondTimestampTwo(new Date());
        String param = "appId="+smsSendConfig.getAppId() +
                "&apiKey="+smsSendConfig.getSign()+"&timestamp="+timestamp;
        log.info("-----param :" + param);
        String sign = (new BASE64Encoder()).encodeBuffer(param.getBytes());
        jsonObject.put("appId",smsSendConfig.getAppId());
        jsonObject.put("timestamp",timestamp);
        jsonObject.put("sign",sign);
        return jsonObject;
    }

    /**
     * 获取精确到秒的时间戳
     * @param date
     * @return
     */
    public static long getSecondTimestampTwo(Date date){
        if (null == date) {
            return 0;
        }
        String timestamp = String.valueOf(date.getTime());
        return Long.valueOf(timestamp);
    }
}
